//
//  StylistRightViewController.m
//  PerfectWorld
//
//  Created by dllo on 16/9/1.
//  Copyright © 2016年 LST. All rights reserved.
//

#import "StylistRightViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface StylistRightViewController ()<UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *allArr;
@property (nonatomic, strong)NSMutableArray *hotArr;
@property (nonatomic, strong)NSMutableArray *cityArr;
@property (nonatomic, strong)NSMutableDictionary *dic;
@property (nonatomic, strong)NSMutableDictionary *locationDic;
@property (nonatomic, strong)CLLocationManager *locationManager;
@property (nonatomic, strong)CLLocation *location;

@end

@implementation StylistRightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.locationDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"定位中..",@"name", nil];
    [self creatLocation];
    [self getPlist];
    [self creatSubView];
    [self creatTableView];
   
}
- (void)creatSubView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
    [self.view addSubview:view];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 2 - 50, 20, 100, 40)];
    label.text = @"城市列表";
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:20];
    [view addSubview:label];
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(10, 20, 50, 30);
    [leftBtn setImage:[UIImage imageNamed:@"返回实线"] forState:UIControlStateNormal];
    [view addSubview:leftBtn];
    [leftBtn addTarget:self action:@selector(clickLeftBtn:) forControlEvents:UIControlEventTouchUpInside];
}
// plist城市列表
- (void)getPlist {
    NSError *error = nil;
    NSString *cityJSON = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"json"];
    NSData *cityData = [NSData dataWithContentsOfFile:cityJSON];
    self.dic = [NSJSONSerialization JSONObjectWithData:cityData options:NSJSONReadingMutableContainers error:&error];
    self.allArr = [_dic objectForKey:@"全部"];
    self.hotArr = [_dic objectForKey:@"热门"];
}
- (void)creatLocation {
    self.locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 10;
    [_locationManager requestAlwaysAuthorization];
    [_locationManager startUpdatingLocation];
    [_locationManager startMonitoringSignificantLocationChanges];
   
}
// 获取当前位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations {
       NSLog(@"经度 = %f 纬度 = %f 高度 = %f", _location.coordinate.latitude,_location.coordinate.longitude, _location.altitude);
    _location = locations[0];
    [self getLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(nonnull NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问失败");
    } else
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法访问");
    }
}
// 121°44’-121°49
// 39°01’-39°04
- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, self.view.bounds.size.width, self.view.bounds.size.height)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _allArr.count + 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"定位";
    } else if (section == 1) {
        return @"热门城市";
    } else {
        return _allArr[section - 2];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return  _hotArr.count;
    } else {
        self.cityArr = _dic[_allArr[section - 2]];
        return _cityArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (indexPath.section == 0) {
        NSString *locationStr = [NSString stringWithFormat:@"%@", _locationDic[@"name"]];
//        NSString *temp2 = [locationStr substringFromIndex:[locationStr length]-1];
//        NSString *str = [locationStr componentsSeparatedByString:temp2];
//       NSString *str = [locationStr componentsSeparatedByString:[NSString stringWithFormat:@"%lu", [locationStr length] - 1 ]];
         cell.textLabel.text = locationStr;
        return cell;
    } else if (indexPath.section == 1) {
        cell.textLabel.text = _hotArr[indexPath.row];
        return cell;
    } else {
        self.cityArr = _dic[_allArr[indexPath.section - 2]];
        cell.textLabel.text = _cityArr[indexPath.row];
        return cell;
    }
}
- (NSArray<NSString *> *) sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *titleArr = [NSMutableArray arrayWithArray:_allArr];
    [titleArr insertObject:@"热" atIndex:0];
    [titleArr insertObject:@"定" atIndex:0];
    return titleArr;
}
- (void)getLocation {
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:_location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                if ([placemarks lastObject].locality.length > 0) {
            // 定位的城市给字典赋值
            NSString *locaName = [[placemarks lastObject].locality substringToIndex:[placemarks lastObject].locality.length];
            [_locationDic setObject:locaName forKey:@"name"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
            });
        }
       
    }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [self dismissViewControllerAnimated:YES completion:^{
        self.cityFilter(cell.textLabel.text);
    }];
}
- (void)clickLeftBtn:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_locationManager stopUpdatingLocation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
